import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

public class Heap {
    public int[] elem;
    public int usedSize;

    public Heap() {
        elem = new int[10];
    }

    public void init(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    //创建大根堆
    public void createBigHeap() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            siftDown(parent, usedSize - 1);
        }
    }

    private void siftDown(int parent, int end) {
        int child = 2 * parent + 1;
        while (child <= end) {
            if (child < end && elem[child] < elem[child + 1]) {
                child++;
            }
            if (elem[child] > elem[parent]) {
                swap(parent, child);
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }

    private void swap(int i, int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    public void offer(int val){
        if(isFull()){
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        elem[usedSize] = val;
        usedSize++;
        siftUp(usedSize-1);
    }
    private boolean isFull(){
        return elem.length == usedSize;
    }
    private void siftUp(int child){
        int parent = (child-1)/2;
        while(parent >= 0){
            if(elem[child] > elem[parent]){
                swap(child,parent);
                child = parent;
                parent = (child-1)/2;
            }else{
                break;
            }
        }
    }
    public int poll(){
        if(isEmpty()){
            return -1;
        }
        int old = elem[0];
        swap(0,usedSize-1);
        usedSize--;
        siftDown(0,usedSize-1);
        return old;
    }
    private boolean isEmpty(){
        return usedSize == 0;
    }

    //返回数组前k个小的元素
    public int[] topK(int[] array,int k){
        int[] tmp = new int[k];
        if(k == 0){
            return tmp;
        }
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new IntCompere());
        for (int i = 0; i < k; i++) {
            priorityQueue.offer(array[i]);
        }
        for (int i = k; i < array.length ; i++) {
            int val = priorityQueue.peek();
            if(val > array[i]){
                priorityQueue.poll();
                priorityQueue.offer(array[i]);
            }
        }
        for(int i = 0;i<k;i++){
            tmp[i] = priorityQueue.poll();
        }
        return tmp;
    }

}
class IntCompere implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}
